﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using Jose;
using ETWebApi2.Models;
using Model;
using BllFactory;
using IBLL;
using System.Configuration;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using BLL;

namespace ETWebApi2.Controllers
{
    public class TokenController : ApiController
    {
        private ICUser_tbService m_cuserServer = ServiceFactory.CreatService<ICUser_tbService>();
        /// <summary>
        /// res 跳转页面(1个人信息2员工管理0我的文件) role 用户角色以及判断(0普通员工1管理员 2布易专用 -1登录密码有误  -2该用户不存在   -3该用户不合法(对应多个活动账号或者系统不存在该用户 -4该公司没有进外发的权限 -5 验证码输入错误) token
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="userPwd"> checkcode</param>
        /// <returns></returns>
        [HttpPost, IPActionFilter,Route("Checkout")]
        public HttpResponseMessage CheckoutUserAndToken()
        {
            HttpContext context = HttpContext.Current;
            string username = context.Request.Params["username"];
            string lockinnum = context.Request.Params["lockinnum"];
            string password = context.Request.Params["password"];

            string ip = context.Request.UserHostAddress;//获取本机ip 也是cookie的名称
            var maxCount = 3;//失败最大次数 -HENEY
            int minutes = 30;//登陆限制时间（分钟） -HENEY

            #region  0717
            int role = 0;
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
                role = -2;
            List<string> result = new List<string>();
            int UserRole = -5;  //验证码输入错误

            //获取登录失败次数，限制登录时间大于当前时间直接跳出-6 -HENEY
            var loginLimit = LoginLimit_tbService.GetLoginLimit(ip);
            if (loginLimit != null)
            {
                if (loginLimit.UnlockTime < DateTime.Now)
                {
                    return CheckOut(username, role, password, loginLimit, maxCount, minutes, ip, result, lockinnum, UserRole);
                }
                else
                {
                    return ObjectToJson.toJson(new { role = role, errCount = loginLimit.ErrCount, unLimitTime = loginLimit.UnlockTime });
                }

            }
            //如果没有登陆限制表没有该IP的数据 -HENEY
            else
            {
                return CheckOut(username, role, password, loginLimit, maxCount, minutes, ip, result, lockinnum, UserRole);
            }
            #endregion
        }


        /// <summary>
        /// 登陆操作
        /// </summary>
        /// <returns></returns>
        private HttpResponseMessage CheckOut(string username, int role, string password, LoginLimit_tb loginLimit, int maxCount, int minutes, string ip, List<string> result, string lockinnum, int UserRole)
        {
            List<CUser_tb> login = m_cuserServer.GetList(u => (u.Phone == username || u.Email == username) && u.State == 1);
            if (login.Count > 0)
            {
                if (login.Count > 1)
                    role = -3;

                if (login[0].UserPwd != password)
                {
                    role = -1;
                    //登陆失败加次数 -HENEY
                    loginLimit = LoginLimit_tbService.UpdateCount(maxCount, minutes, ip);
                }
                else
                {
                    //验证改公司是否有权进外发 
                    result = CheckoutCompany(login[0], lockinnum);
                    if (!string.IsNullOrEmpty(result[1]))
                        UserRole = Convert.ToInt32(result[1]);
                    loginLimit = LoginLimit_tbService.InitializeCount(ip, login[0].Id);
                    return ObjectToJson.toJson(new { role = UserRole, res = result[0], token = result[2], isHaveUpload = new BaseClass().isHaveUploadPage(lockinnum, login[0]), errCount = loginLimit.ErrCount, unLimitTime = loginLimit.UnlockTime });
                }
            }
            else
            {
                role = -2;
                //登陆失败加次数 -HENEY
                loginLimit = LoginLimit_tbService.UpdateCount(maxCount, minutes, ip);
            }
            return ObjectToJson.toJson(new { role = role, errCount = loginLimit.ErrCount, unLimitTime = loginLimit.UnlockTime });
        }


        private List<string> CheckoutCompany(CUser_tb user, string lockInnum)
        {
            ICustomers_tbService cusService = ServiceFactory.CreatService<ICustomers_tbService>();
            Customers_tb cus = cusService.GetList(c => c.Id == user.CompanyId).FirstOrDefault();
            string res = "";
            string role = "";
            string token = "";
            List<string> result = new List<string>();
            if (cus != null && cus.IsDeal > 10)
            {
                HttpContext.Current.Session["LockInNum"] = lockInnum;
                var secret = ConfigurationManager.AppSettings["secret"];
                var payload = new JwtAuthObject()
                {
                    UserId = user.Id,
                    CurentCopmpanyId = (int)user.CompanyId
                };
                //生成 token 
                token = JWT.Encode(payload, Encoding.UTF8.GetBytes(secret), JwsAlgorithm.HS256);
                HttpContext.Current.Session["UserInfo"] = payload;
                if (new BaseClass().isAdmin(user))
                    if (user.UserPwd.Length < 6 || user.UserPwd == "1688M" || user.UserPwd == "1688")
                        //要在个人信息页,提醒用户必须修改为安全的密码 并且一开始就在个人信息界面
                        res = "1";
                if (new BaseClass().isAdmin(user))
                    //进入员工管理界面
                    res = "2";
                else
                    //进入我的文件
                    res = "0";
            }
            else
            {
                role = "-4"; //此公司没有权限使用本系统
            }
            result.Add(res);
            result.Add(role);
            result.Add(token);
            return result;
        }

        /// <summary>
        /// 验证码的绘制 
        /// </summary>
        /// <returns></returns>
        [Route("VerifyCode")]
        [HttpGet]
        public string GetVerifyCode()
        {
            int codeW = 80;
            int codeH = 30;
            int fontSize = 16;
            string chkCode = string.Empty;
            //颜色列表，用于验证码、噪线、噪点 
            Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
            //字体列表，用于验证码 
            string[] font = { "Times New Roman" };
            //验证码的字符集，去掉了一些容易混淆的字符 
            char[] character = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
            Random rnd = new Random();
            //生成验证码字符串 
            for (int i = 0; i < 4; i++)
            {
                chkCode += character[rnd.Next(character.Length)];
            }
            //写入Session、验证码加密
            HttpContext.Current.Session["checkCode"] = chkCode;
            //WebHelper.WriteSession("nfine_session_verifycode", Md5.md5(chkCode.ToLower(), 16));
            //创建画布
            Bitmap bmp = new Bitmap(codeW, codeH);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            //画噪线 
            for (int i = 0; i < 3; i++)
            {
                int x1 = rnd.Next(codeW);
                int y1 = rnd.Next(codeH);
                int x2 = rnd.Next(codeW);
                int y2 = rnd.Next(codeH);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawLine(new Pen(clr), x1, y1, x2, y2);
            }
            //画验证码字符串 
            for (int i = 0; i < chkCode.Length; i++)
            {
                string fnt = font[rnd.Next(font.Length)];
                Font ft = new Font(fnt, fontSize);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0);
            }
            //将验证码图片写入内存流，并将其以Base64 格式输出 
            MemoryStream ms = new MemoryStream();
            try
            {

                bmp.Save(ms, ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                g.Dispose();
                bmp.Dispose();
            }
        }

        private string rootPath = HttpContext.Current.Server.MapPath("~/MenuItemsFile");
        [HttpGet, Route("menu")]
        public HttpResponseMessage GetMenu(string token)
        {
            JwtAuthObject info = new BaseClass().GetInfoByToken(token);
            CUser_tb user = m_cuserServer.GetList(u => u.Id == info.UserId).FirstOrDefault();
            string path = rootPath;
            if (user.Role == 1)
                path += "\\menu.json";
            else
                path += "\\person.json";
            String linee = "";
            using (StreamReader sr = new StreamReader(path, Encoding.UTF8))
            {
                linee = sr.ReadToEnd();
            }
            return ObjectToJson.toJson(linee);
        }

        [HttpGet, Route("info")]
        public HttpResponseMessage GetInfo(string token)
        {
            string path = rootPath + "\\info.json";
            string id = Jose.JWT.Payload(token);
            String linee = "";

            using (StreamReader sr = new StreamReader(path, Encoding.UTF8))
            {
                linee = sr.ReadToEnd();
            }
            return ObjectToJson.toJson(linee);
        }

        [HttpGet, Route("staffmanage")]
        public HttpResponseMessage StaffManage()
        {
            string path = rootPath + "\\staffmanage.json";
            String linee = "";

            using (StreamReader sr = new StreamReader(path, Encoding.UTF8))
            {
                linee = sr.ReadToEnd();
            }
            return ObjectToJson.toJson(linee);
        }


        [HttpGet, Route("all"), JwtAuthActionFilter]
        public HttpResponseMessage GetAll()
        {
            string path = rootPath + "\\all.json";
            String linee = "";
            using (StreamReader sr = new StreamReader(path, Encoding.UTF8))
            {
                linee = sr.ReadToEnd();
            }
            return ObjectToJson.toJson(linee);
        }

        #region 手机短信获取密码
        //忘记密码后重置密码并且手机接收新密码(注意为防止恶意点击频繁发送密码，可规定每个用户每天的次数)
        [HttpGet, Route("forgetpwd")]
        public HttpResponseMessage GetPwd(string username)
        {
            string res = "";
            List<CUser_tb> users = m_cuserServer.GetList(u => u.Phone == username.Replace(" ", "")); //忘记密码
            if (users != null && users.Count > 0)
            {
                //发送密码到手机
                //amzThIYcXZGf 【深圳布易科技】您的用户名是:%P%;密码是:%P%
                string param = string.Format("&p1={0}&p2={1}", users[0].UserName, users[0].UserPwd);
                SendMessage.SendSM(username, "amzThIYcXZGf", param);
                if (users.Count == 1)
                    res = string.Format("密码已发送到{0}手机上,请注意查收。", username);
                else
                    res = string.Format("系统内有多名用户使用此手机号，因此等一下您收到的短信中的姓名可能不正确,但不要紧，请您输入短信中的密码，登陆之后，按照系统提示操作即可", username);
            }
            else
            {
                res = string.Format("系统不存在手机号为{0}的用户。", username);
            }
            return ObjectToJson.toJson(new { status = 200, rel = true, tip = res });
        }
        #endregion
    }
}
